package cn.lysj.framework.common.utils.qrcode;

import cn.hutool.core.util.ImageUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.lysj.framework.common.CommonConstant;
import cn.lysj.framework.common.utils.web.ParamUtil;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author ZhangWenJian
 * @data 2019/1/23--15:32
 * @description
 */
public class QrCode {
    public static String createQrCode(String url) {
//        String url = "https://720nv.com/"; //二维码内容
        int width = 300; //宽
        int height = 300;//高
        String format = "png";//格式
//        Hashtable hints = new Hashtable();
//        hints.put(EncodeHintType.CHARACTER_SET, "utf-8"); //字符集编码
//        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//纠错等级
//        hints.put(EncodeHintType.MARGIN, 2); //边距
        String fileName = "";
        try {
//            BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, width, height, hints);
            BitMatrix bitMatrix = QrCodeUtil.encode(url,width,height);
            String path = CommonConstant.BASE_LOCAL_RESOURCE_IMAGES_DIR + "qrcode/" + getName(); //默认路径+模块+日期
            //缩略图
            String thumbnailPath = path + "/thumbnail/";
            File thumbnailDir = new File(thumbnailPath);
            fileName = ParamUtil.uuid() + ".png";
            File file = new File(path + fileName);//定义图片路径
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            MatrixToImageWriter.writeToFile(bitMatrix, format, file);//在对应路径二维码图片
            if (!thumbnailDir.exists()) {
                thumbnailDir.mkdirs();
            }
            ImageUtil.scale(file, new File(thumbnailPath + fileName), 0.5f);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "qrcode/" + getName() + fileName;
    }

    /**
     * @author drj
     * @date 2018/11/2 14:26
     * @Description:日期格式化
     */
    public static String getName() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("YYYYMM");
        String dateName = dateFormat.format(new Date());
        return dateName;
    }
}
